package com.example.smsbox;

import com.example.database.DatabaseHelper;
import com.example.item.ItemList;
import com.example.utils.Utils;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddContactActivity extends Activity {
	DatabaseHelper db;
	private EditText txtName;
	private EditText txtPhone;
	private Button btnOk;
	private final int PICK = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addcontact);
		db = new DatabaseHelper(this);
		txtName = (EditText) findViewById(R.id.txtName);
		txtPhone = (EditText) findViewById(R.id.txtPhone);
		btnOk = (Button) findViewById(R.id.btnOK);
		btnOk.setOnClickListener(OnClickAdd);
		txtPhone.setOnClickListener(OnClickGetPhoneNumber);
	}
	
	private OnClickListener OnClickAdd = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Utils util = new Utils();
			String str = util.getString(txtPhone.getText().toString());
			ItemList contact = new ItemList(txtName.getText().toString(),str,0);
			if(db.checkPhone(str)==true){
				db.addNewContact(contact);
				Intent intent = new Intent();
				setResult(RESULT_OK,intent);
				finish();
			}else if(db.checkPhone(str)==false){
				Toast.makeText(getApplicationContext(),"So dien thoai da ton tai",Toast.LENGTH_SHORT).show();
			}

		}
	};
	
	private OnClickListener OnClickGetPhoneNumber = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(android.content.Intent.ACTION_PICK);
			intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
			startActivityForResult(intent, PICK);
			
		}
	};
	
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case (PICK):
			if(resultCode==Activity.RESULT_OK){
				Uri contactData = data.getData();
				Cursor c = managedQuery(contactData,null,null,null,null);
				if(c.moveToFirst()){
					String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
					String phone = c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
					txtName.setText(name);
					txtPhone.setText(phone);
				}
			}
			break;
		}
	};
}
